package com.coffee.dict;

import cn.hutool.core.collection.CollectionUtil;
import com.coffee.core.CoffeePage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;

import java.util.List;

/**
 * @author songkui
 * @since 2019/5/8
 */
@Aspect
@AllArgsConstructor
@Slf4j
public class DictPageAspect implements PriorityOrdered {

    private final DictTranslationService dictTranslationService;

    /**
     * 切入点，所有具有DictTranslation的方法
     */
    @Pointcut("@annotation(com.coffee.dict.annotation.CoffeeDictPageAspect)")
    public void dictTranslationPoint() {
    }

    /**
     * 环绕通知方式，拦截方法返回值并进行翻译后返回
     *
     * @param pjp
     * @return 翻译后的值
     * @throws Throwable
     */
    @Around(value = "dictTranslationPoint()")
    public Object translationAround(final ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        if (null == result) {
            log.info("DictPageAspect result object is null");
            return null;
        }
        log.info("DictPageAspect start dict  translation... ");
        if (result instanceof CoffeePage){
            CoffeePage coffeePage = (CoffeePage) result;
            List data = coffeePage.getRecords();
            if (CollectionUtil.isEmpty(data)){
                log.info("DictPageAspect  page data size is empty");
                return result;
            }

            dictTranslationService.translateDict(data);
            return result;
        }else {
            log.error("DictPageAspect error : Non-CoffeePage  cannot be translated ");
            return result;
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
